#version 430 core
#extension GL_EXT_gpu_shader4: enable
#extension GL_EXT_geometry_shader4: enable
layout(triangles)in;
layout(triangle_strip, max_vertices = 3)out;

in vec3 vs_normal[];
in vec3 vs_objPos[];
in vec4 vs_worldPos[];
in vec2 vs_texcoord[];

//uniform mat4 model;
out vec3 gs_normal;
out vec4 gs_worldPos;
out vec2 gs_texcoord;

// 绕轴旋转
void rotation(out mat3 r, in vec3 k, in float theta)
{
    float C = 1-cos(theta);
   	r = mat3( 
       cos(theta)+k.x*k.x*C, -sin(theta)*k.z+k.x*k.y*C, sin(theta)*k.y+k.x*k.z*C,
       sin(theta)*k.z+k.x*k.y*C, cos(theta)+k.y*k.y*C, -sin(theta)*k.x+k.y*k.z*C,
       -sin(theta)*k.y+k.x*k.z*C, sin(theta)*k.x+k.y*k.z*C, cos(theta)+k.z*k.z*C);
	// 列主序，需要转置
	r = transpose(r);
}


void main()
{
    float textureScalingFactor = 0.0007; // 越小点越大
    vec3 v1 = vs_objPos[1].xyz - vs_objPos[0].xyz;
    vec3 v2 = vs_objPos[2].xyz - vs_objPos[0].xyz;
    
    mat3 R12;
    rotation(R12, vec3(0,0,1), acos(dot(normalize(v1),normalize(v2))));
    vec2 gs_texcoord_0 = vec2(0.0f,0.0f);
    vec2 gs_texcoord_1 = vec2(length(v1)*textureScalingFactor,0.0f);
    vec2 gs_texcoord_2 = (R12*vec3(length(v2)*textureScalingFactor, 0.0f, 0.0f)).xy;

    mat3 Rrand;
    // 以坐标作为输入，试图达到随机的效果
    float r_phi = acos(cos(dot(
        (vs_objPos[0]+vs_objPos[1]+vs_objPos[2]), 
        vec3(314.0f,151.0f,834.9f))));

    rotation(Rrand, vec3(0,0,1), r_phi); 

    float r_x = acos(cos(dot(
        (vs_objPos[0]+vs_objPos[1]+vs_objPos[2]), 
        vec3(12.0f,555.0f,123213.9f))));
    float r_y = acos(cos(dot(
        (vs_objPos[0]+vs_objPos[1]+vs_objPos[2]), 
        vec3(7589.0f,464.0f,4214.9f))));
    vec2 move = vec2(r_x, r_y);
    
    gs_texcoord_0 = (Rrand * vec3((gs_texcoord_0 + move), 1.0f)).xy;
    gs_texcoord_1 = (Rrand * vec3((gs_texcoord_1 + move), 1.0f)).xy;
    gs_texcoord_2 = (Rrand * vec3((gs_texcoord_2 + move), 1.0f)).xy;


	gl_Position = gl_PositionIn[0];
    gs_normal = vs_normal[0];
    gs_worldPos = vs_worldPos[0];
    gs_texcoord = gs_texcoord_0;
	EmitVertex();

	gl_Position = gl_PositionIn[1];
    gs_normal = vs_normal[1];
    gs_worldPos = vs_worldPos[1];
    gs_texcoord = gs_texcoord_1;
	EmitVertex();

	gl_Position = gl_PositionIn[2];
    gs_normal = vs_normal[2];
    gs_worldPos = vs_worldPos[2];
    gs_texcoord = gs_texcoord_2;
	EmitVertex();

	EndPrimitive();
}
//
//void main()
//{
//	gl_Position = gl_PositionIn[0];
//    gs_normal = vs_normal[0];
//    gs_worldPos = vs_worldPos[0];
//    gs_texcoord = vs_texcoord[0];
//	EmitVertex();
//
//	gl_Position = gl_PositionIn[1];
//    gs_normal = vs_normal[1];
//    gs_worldPos = vs_worldPos[1];
//    gs_texcoord = vs_texcoord[1];
//	EmitVertex();
//
//	gl_Position = gl_PositionIn[2];
//    gs_normal = vs_normal[2];
//    gs_worldPos = vs_worldPos[2];
//    gs_texcoord = vs_texcoord[2];
//	EmitVertex();
//
//	EndPrimitive();
//}